import {Fragment, PureComponent} from 'react';
import {
  Card,
  Popconfirm,
  Form,
  Row,
  Col,
  Input,
  Button,
  message,
  Select,
  DatePicker,
  Image,
  Tag,
  Badge,
  Tooltip,
  Radio, Divider
} from 'antd';
import React from 'react';
import Icon, {
  CheckCircleOutlined,
  EyeOutlined,
  ShareAltOutlined,
  StopOutlined
} from '@ant-design/icons';
import {connect} from "umi";
import {formatMessage} from "@@/plugin-locale/localeExports";
import ProTable from '@ant-design/pro-table';
import styles from '../common.less';
import {hasPermission, nopermission} from "@/hasPermission";
import moment from "moment";
import {history} from "@@/core/history";


class BlogExamine extends PureComponent{

  state = {
    formValues: {},
    updateFormValues: {},
    currentPage: 1,
    pageSize: 10,
    startTime: null,
    endTime: null
  }

  columns = [
    {
      title: formatMessage({ id: 'app.blog.title' }),
      dataIndex: 'title',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.blog.loginName' }),
      dataIndex: 'loginName',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.blog.cover' }),
      dataIndex: 'cover',
      align: 'center',
      render: (text, record) => (text != '-' && text != '' && text != 0) ? <Image width={100} height={50} src={text}/> : '无封面'
    },
    {
      title: formatMessage({ id: 'app.blog.label' }),
      dataIndex: 'label',
      align: 'center',
      render: (text, record) => text && text.split(',').map((val) => <Tag color="processing">{val}</Tag>)
    },
    {
      title: formatMessage({ id: 'app.blog.type' }),
      dataIndex: 'type',
      align: 'center',
      render: (text, record) => text && text.split(',').map((val) => <Tag color="success">{val}</Tag>)
    },
    {
      title: formatMessage({ id: 'app.blog.createTime' }),
      dataIndex: 'createTime',
      align: 'center',
      width: 110,
      render: (text, record) => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
    },
    {
      title: formatMessage({ id: 'app.blog.status' }),
      dataIndex: 'status',
      align: 'center',
      width: 110,
      render: (text, record) =>
      <Tooltip title={record.examineTime ? `审核时间: ${moment(record.examineTime).format('YYYY-MM-DD HH:mm:ss')}` : '未审核'}>
        <Badge
          status={text == 1 ? 'processing' : (text == 2 ? 'success' : (text == 3 ? 'warning' : 'error'))}
          text={text == 1 ? '待审核' : (text == 2 ? '审核通过' : (text == 3 ? '审核不通过' : '已封禁'))}
        />
      </Tooltip>
    },
    {
      title: formatMessage({ id: 'app.blog.starCount' }),
      dataIndex: 'starCount',
      width: 70,
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.blog.likeCount' }),
      dataIndex: 'likeCount',
      width: 70,
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.blog.views' }),
      dataIndex: 'views',
      width: 70,
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: 130,
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.toBlogInfo(record.id)}><EyeOutlined />&nbsp;查看</a>
          <Divider type='vertical' />
          {record.status == 1 ?
          <Popconfirm
            title='是否通过？'
            okText='通过'
            cancelText='不通过'
            onConfirm={() => this.examine(record.id, 2)}
            onCancel={() => this.examine(record.id, 3)}
          >
            <a>
              <ShareAltOutlined />
              &nbsp;{formatMessage({ id: 'app.common.examine' })}
            </a>
            </Popconfirm> : (record.status == 2 ?
              <Popconfirm
              title='是否封禁？'
              onConfirm={() => this.examine(record.id, 0)}
            >
              <a>
                <StopOutlined />
                &nbsp;封禁
              </a>
            </Popconfirm> :
              <Popconfirm
                title='是否解封？'
                onConfirm={() => this.examine(record.id, 1)}
              >
                <a>
                  <CheckCircleOutlined />
                  &nbsp;解封
                </a>
              </Popconfirm>)
          }
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'blogExamine/fetch'
    })
    this.formRef = React.createRef();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    if (sorter.field && sorter.order) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({ currentPage: pagination.current, pageSize: pagination.pageSize });
    dispatch({
      type: 'blogExamine/fetch',
      payload: params
    });
  };

  handleSearch = e => {
    const { dispatch } = this.props;
    const values = {
      ...e
    };
    this.setState({
      formValues: values
    });
    if (e == null) {
      values.currentPage = this.state.currentPage;
      values.pageSize = this.state.pageSize;
    } else {
      values.currentPage = 1;
      values.pageSize = 10;
    }
    dispatch({
      type: 'blogExamine/fetch',
      payload: values
    });
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.setState({
      formValues: {},
      currentPage: 1,
      pageSize: 10,
      startTime: null,
      endTime: null
    });
    dispatch({
      type: 'blogExamine/fetch'
    });
  };

  examine = (id, status) => {
    if (!hasPermission('admin:update')){
      nopermission();
      return ;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'blogExamine/updateBlog',
      payload: {
        id: id,
        status: status,
        examineTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }
    }).then(res => {
      if (res.status == 200){
        message.success('操作成功!');
        this.handleFormReset();
      }
    });
  };

  toBlogInfo = (id) => {
    history.push('/blogInfo?id=' + id);
  };

  renderSimpleForm() {

    const options = [
      { label: '待审核', value: 1 },
      { label: '审核通过', value: 2 },
      { label: '审核不通过', value: 3 },
    ];

    return (
      <Form ref={this.formRef} onFinish={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.blog.loginName' })} name='loginName'>
              <Input placeholder={formatMessage({ id: 'app.blog.loginName' })} />
            </Form.Item>
          </Col>
          <Col md={10} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.blog.status' })} name='status'>
              <Radio.Group options={options} optionType="button" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>
                <Icon type='search'/>{formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type='primary'
              >
                <Icon type='reload'/>{formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      blogExamine: {data},
      loading
    } = this.props;

    return (
      <>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <ProTable
            bordered={true}
            search={false}
            rowKey={record => record.id}
            loading={loading}
            dataSource={data ? data.list : []}
            pagination={data ? data.pagination : {}}
            columns={this.columns}
            onChange={this.handleBasicTableChange}
            options={{
              density: true,
              reload: () => {
                this.handleSearch();
              },
              fullScreen: true,
              setting: true
            }}
          />
        </div>
      </Card>
      </>
    )
  }
}

export default connect(({ blogExamine, loading }) => ({
  blogExamine,
  loading: loading.effects['blogExamine/fetch']
}))(BlogExamine);
